/*
 * To change this template, choose Tools | Templates and open the template in
 * the editor.
 */
package goodenglish.domain.service;

import goodenglish.infrastructure.Config;
import goodenglish.infrastructure.TranslatorCache;
import goodenglish.infrastructure.repository.db.TranslatorCacheDb;
import goodenglish.interfaces.BeanFactory;

import java.io.FileNotFoundException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.memetix.mst.language.Language;
import com.memetix.mst.translate.Translate;
import com.msino.dict.StarDictReader;
import com.msino.dict.manager.DictsManager;
import com.msino.dict.service.IDictsManager;
import com.msino.dict.service.core.Word;
import com.msino.dict.service.exception.NotFoundWordException;

/**
 * 提供翻译功能翻译
 * 
 * @author 关攀攀 panpan_001@126.com
 */
public class Translator {

	private static Log logger = LogFactory.getLog(Translator.class);

	private static StarDictReader instance;
	private TranslatorCache translatorCache= BeanFactory.getSingleInstance(TranslatorCacheDb.class);

	/**
	 * 把英语翻译成汉语
	 * 
	 * @param engWord
	 * @return
	 */
	public String englishToChiniseMs(String engWord) {

		/**
		 * 先从缓存得
		 */
		String explain = translatorCache.getExplain(engWord);
		if (null != explain) {
			return explain;
		}
		// Set the Microsoft Translator API Key - Get yours at
		// http://www.bing.com/developers/createapp.aspx
		Translate.setKey("2D449BBFDC549C5FF628624270301DDE713F031B");
		try {
			explain = Translate.execute(engWord, Language.ENGLISH,
					Language.CHINESE_SIMPLIFIED);
			translatorCache.addExplain(engWord, explain);
		} catch (Exception ex) {
		}
		return (null == explain) ? "微软无解释" : explain;
	}

	

	/**
	 * 把英语翻译成汉语
	 * 
	 * @param engWord
	 * @return
	 */
	public String englishToChiniseLocal(String engWord) {
		String explain = "";
		logger.info("start  englishToChiniseLocal:" + engWord);
		if (null == instance) {
			logger.info("initialize  StarDictReader:");
			IDictsManager dictsManager = new DictsManager();
			String dictsProp = dictsManager.getDictProps();
			String dictFileDir = Config.DICT_PATH;
			String dictName = Config.DICT_NAME;
			// dictFileDir = dictsProp.substring(0, dictsProp.indexOf("||"));
			// DICT_NAME = dictsProp.substring(dictsProp.indexOf("||") + 2,
			// dictsProp.length());

			logger.info("dictFileDir : " + dictFileDir);
			logger.info("dictName : " + dictName);

			try {
				instance = new StarDictReader(dictFileDir, dictName);
			} catch (FileNotFoundException ex) {
				logger.error(ex.getStackTrace());
			}
		}

		Word result = null;
		try {
			result = instance.lookup(engWord);
		} catch (NotFoundWordException ex) {

			explain = "找不到解释";
		}
		if (null != result) {
			explain = result.definition;
		}
		return explain;

	}
}
